package by.semerikov.data;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import by.semerikov.exceptions.ConnectorException;
import by.semerikov.exceptions.DAOException;
import by.semerikov.model.Person;
import by.semerikov.model.UserSession;
import by.semerikov.service.PersonService;
import by.semerikov.service.ServiceFactory;
import by.semerikov.service.UserSessionService;


public class SessionHandler {
	private HttpSession session ;
	HttpServletRequest request;
	
	public SessionHandler(HttpServletRequest request) {
		this.request = request;
		session = request.getSession(true);
	}
	
	public void setIndex(String value)
	{
		if(session != null)
		{
			session.setAttribute("index",value);
		}
	}
	
	public void setUserName(String value)
	{
		if(session != null)
		{
			session.setAttribute("userName",value);
		}
	}
	
	public void setRole(String value)
	{
		if(session != null)
		{
			session.setAttribute("role",value);
		}
	}
	
	public String getRole()
	{
		if(session != null)
		{
			return (String) session.getAttribute("role" );
		}
		return null;
	}
    
	public Person getUser() throws DAOException, ConnectorException
	{
		Person result = null;
		Object tempObj =   session.getAttribute("index");
		if(tempObj != null&& tempObj instanceof String)
		{
			String index = (String) tempObj;
				UserSessionService userSessionService = ServiceFactory.getInstance().getUserSessionService();
				PersonService personService = ServiceFactory.getInstance().getPersonService();
				List< UserSession> temp = userSessionService.readUserSession(new UserSession(null, null, index));
				if (temp != null && temp.size()>0)
				{
					UserSession usersIndexId = temp.get(0);
					List< Person> lp = personService.getPersonsEqual(new Person(usersIndexId.getUserId(), null, null, null, null, null));
					if (lp != null && lp.size()>0)
					{
						result = lp.get(0);
					}
				}	
		}
		return result;
		
	}
	
	public void DeleteSession() throws DAOException, ConnectorException
	{
		Object tempObj =   session.getAttribute("index");
		if(tempObj != null&& tempObj instanceof String)
		{
			String index = (String) tempObj;
				UserSessionService userSessionService = ServiceFactory.getInstance().getUserSessionService();
				List< UserSession> temp = userSessionService.readUserSession(new UserSession(null, null, index));
				if (temp != null && temp.size()>0)
					userSessionService.deleteUserSession(temp.get(0));
			
		}
		session.removeAttribute("index");
		session.invalidate();
	}
}
